package main

import (
	"github.com/go-co-op/gocron"
	"io/ioutil"
	"log"
	"net/http"
	"strings"
	"tiger-ddns/src/config"
	"tiger-ddns/src/ddns/oray"
	"time"
)

const (
	CheckIps = "https://ddns.oray.com/checkip"
	//CheckIps = "https://api.ipify.org,https://ident.me"
)

func main() {
	config, err := config.GetConfig()
	if err != nil {
		log.Fatalf("⚠️ 读取配置文件失败, %v", err)
	}

	s := gocron.NewScheduler(time.UTC)
	s.Every(config.InterVal).Seconds().Do(func() {
		currentIP := fetchIP()
		if currentIP == "" {
			log.Fatal("⚠️ IP获取失败，检查网络连接")
			return
		} else {
			log.Printf("🍇 当前IP：%s", currentIP)
		}
		oray.Update(config, currentIP)
	})
	s.StartBlocking()
}

// 获取公网ip
func fetchIP() string {
	sources := strings.Split(CheckIps, ",")
	for _, url := range sources {
		resp, err := http.Get(url)
		if err == nil {
			defer resp.Body.Close()
			ip, _ := ioutil.ReadAll(resp.Body)
			return string(ip)
		}
	}
	return ""
}
